//
//  BulletManager.m
//  Project5
//
//  Created by Nguyen Tan Loc on 5/20/13.
//  Copyright (c) 2013 Nguyen Tan Loc. All rights reserved.
//

#import "BulletManager.h"

@implementation BulletManager
@synthesize _arrActiveBullet = m_ArrActiveBullet;

-(id) init
{
    if (self == [super init])
    {
        m_ArrActiveBullet = [[NSMutableArray alloc] init];
        m_ArrInactiveBullet = [[NSMutableArray alloc] init];
        
        [self prepareBullet];
        [self schedule:@selector(updateBullet) interval:0.1f];
    }
    
    return self;
}

-(void) updateBullet 
{
    for (int i = 0; i < m_ArrActiveBullet.count; i++)
    {
        Bullet *b = [m_ArrActiveBullet objectAtIndex:i];
        if (b._state == STATE_IDLE)
        {
            [m_ArrActiveBullet removeObject:b];
            [m_ArrInactiveBullet addObject:b];
            [b randomColor];
        }
    }
}

-(Bullet *) createRandomBullet
{
    Bullet *b = [[[Bullet alloc] initWithType:BULLET_TYPE_NORMAL color:0] autorelease];
    [b randomColor];
    return  b;
}

-(void) prepareBullet
{
    if (m_ArrInactiveBullet.count < 6)
    {
        for (int i = m_ArrInactiveBullet.count; i < 6; i++)
        {
            Bullet *b = [self createRandomBullet];
            [self addChild:b];
            [m_ArrInactiveBullet addObject:b];
        }
    }
//    CCLOG(@"%d --- %d", m_ArrInactiveBullet.count, m_ArrActiveBullet.count);
    [self arrangeBullet];
}

-(void) arrangeBullet
{
    for (int i = 0; i < m_ArrInactiveBullet.count; i++)
    {
        Bullet *b = [m_ArrInactiveBullet objectAtIndex:i];
        [b setPosition:ccp(-50 * i, 30 - 374)];
        [b setVisible:(i < 6 ? YES : NO)];
    }
    
    Bullet *currentBullet = [m_ArrInactiveBullet objectAtIndex:0];
    [currentBullet setPosition:ccp(0, 0)];
    [currentBullet appear];
}

-(void) fireCurrentBulletWithAngle:(float)a
{
    Bullet *b = [m_ArrInactiveBullet objectAtIndex:0];
    [m_ArrInactiveBullet removeObject:b];
    [m_ArrActiveBullet addObject:b];
    
    [b fireWithAngle:a];
    [self prepareBullet];
}

-(void) dealloc
{
    [super dealloc];
    
    [m_ArrActiveBullet removeAllObjects];
    [m_ArrActiveBullet release];
    m_ArrActiveBullet = nil;
    
    [m_ArrInactiveBullet removeAllObjects];
    [m_ArrInactiveBullet release];
    m_ArrInactiveBullet = nil;
}

@end
